<template>
  <a-layout>
    <a-spin tip="加载中.." :spinning="spinning" :delay="300">
      <!-- 头部区域 -->
      <PageHeader @back="$router.go(-1)" subTitle="返回">{{ pageTitle }}</PageHeader>
      <!-- 内容区域 -->
      <div style="padding: 15px 150px">
        <!-- 公告标题 start -->
        <p class="bleft">公告标题</p>
        <p
          style="
            font-size: 12px;
            font-family: SourceHanSansCN-Regular, SourceHanSansCN;
            font-weight: 400;
            color: #767885;
            line-height: 18px;
          "
        >
          输入标题请不要超过35个字。
        </p>
        <a-input
          v-model="caeatForm.title"
          style="width: 336px; margin-right: 15px"
          :max-length="35"
          placeholder="请输入公告标题"
          allow-clear
        />
        <a-checkbox v-model="caeatForm.isTop">公告置顶</a-checkbox>
        <!-- 公告标题 ent -->
        <!-- 内容 start -->
        <p class="bleft">内容</p>
        <VueWangeditor
          @change="VueWangeditor"
          :fileListVal="fileList"
          @saveFileList="saveFileList"
          v-model="caeatForm.contentHasStyle"
          style="z-index: 10; margin: 0"
          class="wangeditor"
          ref="editorStyle"
        />
        <!-- 内容 end -->
        <!-- 员工类型 start -->
        <p class="bleft">员工类型</p>
        <a-radio-group v-model="caeatForm.formalType" @change="groupChange">
          <a-radio :value="2">正式</a-radio>
          <a-radio :value="1">试用</a-radio>
        </a-radio-group>
        <!-- 员工类型 end -->
        <!-- 发布范围 start -->
        <p class="bleft">发布范围</p>
        <a-radio-group v-model="caeatForm.publishEmpRangeIsAll" @change="changePublishEmpRangeIsAll">
          <a-radio :value="true">全公司</a-radio>
          <a-radio :value="false">指定范围</a-radio>
        </a-radio-group>
        <a-button v-if="!caeatForm.publishEmpRangeIsAll" style="margin-right: 15px" @click="selectMember">选择人员</a-button>
        <span v-if="!caeatForm.publishEmpRangeIsAll"
          >已选择 {{ defaultSelectedKeys | SelectedString }}等 {{ selectedList.length }} 个人</span
        >

        <span v-if="fold && !caeatForm.publishEmpRangeIsAll" class="fold" @click="fold = false">
          收起
          <a-icon type="arrow-up" />
        </span>
        <span v-if="!fold && !caeatForm.publishEmpRangeIsAll" class="fold" @click="fold = true">
          展开
          <a-icon type="arrow-down" />
        </span>
        <a-table
          v-if="fold == true"
          :columns="memberColumn"
          :data-source="selectedList"
          :scroll="{ y: 320 }"
          row-key="id"
          style="margin-top: 12px; width: 95%"
        />
        <a-modal title="选择人员" :width="800" :visible="staffVisible" @cancel="staffVisible = false">
          <template slot="footer">
            <a-button @click="staffUp">上一步</a-button>

            <a-button key="submit" type="primary" @click="staffHandleOk">确认</a-button>
          </template>

          <div style="display: flex">
            <div style="border-right: 1px solid #d8d8d8; flex: 1; padding: 0 15px">
              <a-input-search v-model="staffFrom.nameOrPhone" placeholder="搜索人员或手机号" @search="onSearch" />
              <div @click="onCheckAll" style="cursor: pointer; margin: 5px">
                全选当页
                <i v-if="checkAll" style="font-size: 19px" class="iconfont icon-check-circle-fill primary_color"></i>
                <img v-else src="@/assets/icons/未选择.png" style="width: 18px; height: 18px" />
              </div>
              <div style="height: 420px; overflow-y: auto; padding: 0 15px">
                <div
                  @click="onRow(item)"
                  v-for="(item, index) in staffData"
                  :key="index"
                  style="cursor: pointer; height: 40px; display: flex; justify-content: space-between; align-items: center"
                >
                  <span>
                    <a-avatar :src="item.empPhoto" size="small" style="margin-right: 5px" icon="user" />
                    {{ item.name }}{{ item.phone }}
                  </span>

                  <i v-if="item.isTrue" style="font-size: 19px" class="iconfont icon-check-circle-fill primary_color"></i>
                  <img v-else src="@/assets/icons/未选择.png" style="width: 18px; height: 18px" />
                </div>
              </div>
              <a-pagination
                size="small"
                :total="pageCount"
                :current="staffFrom.pageNo"
                show-size-changer
                :show-total="(total) => `共 ${pageCount} 条`"
                :pageSizeOptions="['10', '20', '50', '100']"
                @change="onChangePagination"
                @showSizeChange="showSizeChange"
              />
            </div>
            <div style="flex: 1; padding: 0 15px">
              <div style="margin-bottom: 15px">
                已选择的人员
                <span class="primary_color">{{ staffrightData.length }}人</span>

                <div style="height: 420px; overflow-y: auto; padding: 0 15px">
                  <div
                    v-for="(item, index) in staffrightData"
                    :key="index"
                    style="cursor: pointer; height: 40px; display: flex; justify-content: space-between; align-items: center"
                  >
                    <span>
                      <a-avatar :src="item.empPhoto" size="small" style="margin-right: 5px" icon="user" />
                      {{ item.name }}{{ item.phone }}
                    </span>

                    <img @click="deleteItem(item, index)" src="@/assets/icons/删除.png" style="width: 18px; height: 18px" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-modal>
        <a-modal :width="800" title="选择人员" :visible="visible" :confirm-loading="confirmLoading" @cancel="handleCancel">
          <template slot="footer">
            <a-button key="back" @click="handleCancel">取消</a-button>
            <a-button type="primary" v-if="!caeatForm.publishEmpTypeIsAll" @click="xiayibu">下一步</a-button>
            <a-button v-if="caeatForm.publishEmpTypeIsAll" key="submit" type="primary" :loading="confirmLoading" @click="handleOk"
              >确认</a-button
            >
          </template>
          <template v-if="!isJF">
            <p class="bleft">员工性质</p>
            <a-checkbox-group v-model="caeatForm.publishEmpType" name="checkboxgroup" :options="$store.state.enums.postTypeLst" />
          </template>
          <p class="bleft">发布范围</p>
          <a-radio-group v-model="caeatForm.publishEmpTypeIsAll" @change="publishEmpTypeIsAllChange">
            <a-radio :value="true">全部人员</a-radio>
            <a-radio :value="false">部分人员</a-radio>
          </a-radio-group>
        </a-modal>

        <!-- 发布范围 end -->
        <!-- 发布时间 start-->
        <p class="bleft">发布时间</p>
        <a-radio-group v-model="caeatForm.isPublishNow">
          <a-radio :value="true">立即发布</a-radio>
          <a-radio :value="false">定时发布</a-radio>
        </a-radio-group>
        <a-space>
          <a-date-picker
            v-model="caeatForm.publishDate"
            show-time
            v-if="!caeatForm.isPublishNow"
            placeholder="发布时间"
            @change="onChangeDate"
            @ok="onOk"
          />
        </a-space>
        <!-- 发布时间 end-->
        <!-- 推送设置 start-->
        <p class="bleft">推送设置</p>
        <!-- 推送设置 end-->
        <a-checkbox-group :options="options" v-model="caeatForm.noticeType" />
      </div>
      <a-divider />
      <div style="text-align: right; margin-right: 20px; margin-bottom: 15px">
        <a-space>
          <a-button v-if="$route.query.sign === '0'" @click="$router.go(-1)">取消</a-button>
          <a-button v-if="$route.query.sign === '1' && caeatForm.status === 2" @click="onDet">删除</a-button>
          <a-button v-if="$route.query.sign === '1' && caeatForm.status !== 2" @click="offline">下线</a-button>
          <a-button v-if="$route.query.sign === '1' && caeatForm.status === 2" @click="online">上线</a-button>
          <a-button type="primary" @click="preview" v-if="$route.query.sign === '0'">预览</a-button>
          <a-button type="primary" v-if="$route.query.sign === '1'" @click="save">保存</a-button>
          <a-button type="primary" @click="publish" v-if="$route.query.sign === '0'">确认发布</a-button>
        </a-space>
      </div>
      <!-- 预览 -->
      <a-modal title="预览" :visible="previewVisible" @ok="() => (previewVisible = false)" @cancel="() => (previewVisible = false)">
        <div class="notice-editor-wrapper">
          <div class="ql-editor-content">
            <div class="preview-box" :style="bgImage">
              <div class="notice-content">
                <div class="notice-company-title">{{ caeatForm.title }}</div>
                <div class="notice-company-date">
                  <span>{{ caeatForm.title.publishDate }}</span>
                </div>
                <div class="notice-company-content" v-html="caeatForm.contentHasStyle" />
              </div>
            </div>
          </div>
        </div>
      </a-modal>
    </a-spin>
  </a-layout>
</template>

<script>
import { mapGetters } from "vuex";
import moment from "moment";
import "moment/locale/zh-cn";
import {
  onlineNotice,
  deleteSysNotice,
  offlineNotice,
  updateSysNotices,
  screenEmployees,
  getNoticeById,
  getPageEmpList
} from "@/api/company/index";
import VueWangeditor from "@/components/ZXR/vueWangeditor";
export default {
  components: { VueWangeditor },
  data() {
    return {
      fileList: [],
      spinning: false,
      previewVisible: false,
      bgImage: {
        backgroundImage: "url(" + require("@/assets/img/iphone.png") + ")",
        backgroundRepeat: "no-repeat",
        backgroundSize: "100% 100%"
      },
      checkAllText: "全选当页",
      staffVisible: false,
      staffrightData: [],
      staffData: [],
      staffFrom: {
        postType: "",
        companyId: "",
        pageNo: 1,
        pageSize: 10
      },
      checkAll: false,
      visible: false,
      confirmLoading: false,
      treeData: [],
      tabbleData: [],
      pageCount: 0,
      pageTitle: "",
      // 内容区域
      caeatForm: {
        companyId: "", // 公司id
        content: "", // 公告内容
        contentHasStyle: "", // 带样式的公告内容
        finalUserIds: "", // 员工对应的用户
        isPublishNow: true, // 公告立即发布
        formalType: 2, // 员工正式类型(1 正式 2试用 0无状态)
        isTop: false, // 是否置顶(1:置顶,0:不置顶)
        noticeType: ["1"], // 通知类型
        offlineDate: "", // 下线时间
        props: "", // 补充信息
        publishDate: "", // 发布时间
        publishEmpIds: [], // 公告发布范围,员工id(部分员工时使用)
        publishEmpRange: "", // 部分发布的时候选择的员工id(用,分隔)
        publishEmpRangeIsAll: true, // 是否全公司发布(1:全公司,0:部分员工)
        publishEmpType: [], // 部分员工类型时选择的员工类型code(用,分隔)
        publishEmpTypeIsAll: true, // 是否全部员工类型发布(1:全部员工类型,0:部分员工类型)
        publishUserId: "", // 发布公告的用户id
        title: "", // 公告标题
        topDateCreate: "" // 发起置顶时间
      },
      options: [
        { label: "微信", value: "1" }
        // { label: "短信", value: "2" },
        // { label: "邮件", value: "3" }
      ],
      fold: false,
      chooseMemberVisible: false,
      defaultSelectedKeys: [],
      selectedList: [],
      memberColumn: [
        {
          title: "员工姓名",
          dataIndex: "name",
          align: "center",
          width: 200
        },
        {
          title: "身份证号",
          dataIndex: "idCard",
          align: "center",
          width: 200,
          customRender: (text) => {
            return text != null ? text : "--";
          }
        },
        {
          title: "人员性质",
          dataIndex: "postType",
          align: "center",
          width: 200,
          customRender: (text) => {
            return this.$store.state.enums.postTypeArr[text - 1];
          }
        },
        {
          title: "手机号码",
          dataIndex: "phone",
          align: "center",
          width: 250,
          customRender: (text) => {
            return text != null ? text : "--";
          }
        }
      ],
      dateString: ""
    };
  },
  computed: {
    ...mapGetters(["isJF"])
  },
  filters: {
    SelectedString(data) {
      const _data = JSON.parse(JSON.stringify(data));
      let str = "";
      if (_data.length > 0) {
        str = _data
          .slice(0, 2)
          .map((item) => item.name)
          .join(",");
      }

      return str;
    }
  },
  created() {
    this.caeatForm.companyId = this.$store.state.hr.companyId;
    if (this.$route.query.sign === "0") {
      this.pageTitle = "新建公告";
    } else {
      this.pageTitle = "详情";
      this.getNoticeByIdDel(this.$route.query.id);
    }
  },
  methods: {
    saveFileList(data) {
      this.fileList = data;
    },
    groupChange() {
      this.staffrightData = [];
      this.staffData = [];
      this.selectedList = [];
    },
    // 预览
    preview() {
      this.previewVisible = true;
    },
    publishEmpTypeIsAllChange(e) {
      this.caeatForm.publishEmpTypeIsAll = e.target.value;
    },

    onDet() {
      deleteSysNotice(this.caeatForm.id)
        .then((res) => {
          this.$message.success("删除成功!");
          this.$router.go(-1);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    online() {
      onlineNotice(this.caeatForm.id)
        .then((res) => {
          this.getNoticeByIdDel(this.$route.query.id);
          this.$message.success("上线成功!");
        })
        .catch((err) => {
          this.$message.error("上线失败!");
          console.log("debug log --> ", err);
        });
    },
    // 下线
    offline() {
      offlineNotice(this.caeatForm.id)
        .then((res) => {
          this.$refs.editorStyle.isTxt = true;
          this.getNoticeByIdDel(this.$route.query.id);
          this.$message.success("下线成功!");
        })
        .catch((err) => {
          this.$message.error("下线失败!");
          console.log("debug log --> ", err);
        });
    },
    // 修改
    save() {
      console.log(this.caeatForm.contentHasStyle);
      const caeatForm = JSON.parse(JSON.stringify(this.caeatForm));
      caeatForm.empInfoList = caeatForm.empInfoList.map((z) => z.id);
      caeatForm.publishEmpIds = caeatForm.empInfoList;
      caeatForm.file = JSON.stringify(this.fileList);
      caeatForm.publishEmpType = caeatForm.publishEmpType.length > 0 ? caeatForm.publishEmpType.join(",") : "";
      caeatForm.noticeType = caeatForm.noticeType.length > 0 ? caeatForm.noticeType.join(",") : "";
      caeatForm.publishEmpRange =
        caeatForm.publishEmpIds && caeatForm.publishEmpIds.length > 0 ? JSON.parse(JSON.stringify(caeatForm.publishEmpIds)).join(",") : "";
      if (caeatForm.isPublishNow === true) {
        caeatForm.publishDate = moment(moment().add(1, "seconds")).format("YYYY-MM-DD HH:mm:ss");
      }
      updateSysNotices(caeatForm)
        .then((res) => {
          this.$router.go(-1);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 全选当前页面
    onCheckAll() {
      this.checkAll = !this.checkAll;
      if (this.checkAll) {
        this.staffData.forEach((element) => {
          if (!element.isTrue) {
            this.onRow(element);
          }
        });
      } else {
        this.staffData.forEach((element) => {
          if (element.isTrue) {
            this.deleteItem(element);
          }
        });
      }
    },
    deleteItems(item) {
      this.staffrightData.forEach((element, index) => {
        if (item.id === element.id) {
          this.staffrightData.splice(index, 1);
        }
      });
    },
    deleteItem(item, index) {
      this.staffrightData.splice(index, 1);
      this.staffData.forEach((element) => {
        if (element.id === item.id) {
          element.isTrue = false;
          this.checkAll = false;
        }
      });
    },
    onSearch() {
      this.staffFrom.pageNo = 1;
      this.getPageEmpLists();
    },
    showSizeChange(current, size) {
      this.staffFrom.pageNo = 1;
      this.staffFrom.pageSize = size;
      this.getPageEmpLists();
    },
    onChangePagination(pageNumber) {
      this.staffFrom.pageNo = pageNumber;
      this.getPageEmpLists();
    },
    onRow(item) {
      item.isTrue = !item.isTrue;
      if (item.isTrue) {
        let num = 0;
        this.staffData.forEach((element) => {
          if (element.isTrue) {
            num += 1;
          }
        });
        this.checkAll = this.staffData.length === num;

        const arr = this.staffrightData.filter((items) => items.id === item.id);
        if (arr.length === 0) {
          this.staffrightData.push(item);
        }
      } else {
        this.checkAll = false;
        this.staffrightData.forEach((element, index) => {
          if (item.id === element.id) {
            this.staffrightData.splice(index, 1);
          }
        });
      }
    },
    staffHandleOk() {
      this.selectedList = JSON.parse(JSON.stringify(this.staffrightData));
      if (this.selectedList.length === 0) {
        this.$message.error("请选择员工");
        return;
      }
      this.staffVisible = false;

      const arr = [];
      this.selectedList.forEach((element) => {
        arr.push(element.id);
      });
      this.caeatForm.publishEmpIds = arr;
    },
    staffUp() {
      this.visible = true;
      this.staffVisible = false;
    },
    getPageEmpLists() {
      this.staffFrom.postType = JSON.parse(JSON.stringify(this.caeatForm.publishEmpType)).join(",");
      this.staffFrom.companyId = this.$store.state.hr.companyId;
      this.staffFrom.formalType = this.caeatForm.formalType;

      getPageEmpList(this.staffFrom)
        .then((res) => {
          this.visible = false;
          this.staffVisible = true;
          res.data.entities.forEach((element, index) => {
            res.data.entities[index].isTrue = false;
          });
          console.log(this.staffrightData, res);
          this.staffrightData.forEach((element) => {
            res.data.entities.forEach((esy) => {
              if (element.id === esy.id) {
                esy.isTrue = true;
              }
            });
          });
          this.staffData = res.data.entities;
          this.pageCount = res.data.entityCount;

          const arr = this.staffData.filter((item) => item.isTrue);
          this.checkAll = !!(arr.length === this.staffData.length && arr.length !== 0);
          console.log("arr", arr, this.checkAll);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    xiayibu() {
      if (this.caeatForm.publishEmpType.length === 0 && !this.isJF) {
        this.$message.error("请选择员工性质");
        // this.staffFrom.postType = "";
      } else {
        this.getPageEmpLists();
      }
    },
    handleOk(e) {
      // this.confirmLoading = true;
      // setTimeout(() => {
      //   this.visible = false;
      //   this.confirmLoading = false;
      //   this.staffrightData = [];
      //   this.staffData = [];
      //   this.selectedList = [];
      // }, 100);
      if (this.caeatForm.publishEmpType.length === 0 && !this.isJF) {
        this.$message.error("请选择员工性质");
      } else {
        this.getPensionOk();
      }
    },
    getPensionOk() {
      this.staffFrom.postType = JSON.parse(JSON.stringify(this.caeatForm.publishEmpType)).join(",");
      this.staffFrom.companyId = this.$store.state.hr.companyId;
      this.staffFrom.formalType = this.caeatForm.formalType;
      this.staffFrom.pageSize = 1000;
      console.log(this.staffFrom);
      getPageEmpList(this.staffFrom)
        .then((res) => {
          // console.log("res", res);
          res.data.entities.forEach((element, index) => {
            res.data.entities[index].isTrue = true;
          });
          this.staffData = res.data.entities;
          this.staffrightData = this.staffData;
          this.staffHandleOk();

          this.visible = false;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    handleCancel(e) {
      this.visible = false;
    },
    getNoticeByIdDel(id) {
      this.spinning = true;
      getNoticeById(id)
        .then((res) => {
          if (res.data.publishDate) {
            res.data.publishDate = moment(parseInt(res.data.publishDate)).format("YYYY-MM-DD hh:mm:ss");
          }
          res.data.joinCityCode = res.data.joinCityCode ? res.data.joinCityCode.split(",") : [];
          res.data.publishEmpType = res.data.publishEmpType ? res.data.publishEmpType.split(",") : [];
          res.data.noticeType = res.data.noticeType ? res.data.noticeType.split(",") : [];
          res.data.isPublishNow = false;
          this.caeatForm = res.data;
          this.fileList = JSON.parse(res.data.file);
          this.selectedList = res.data.empInfoList;
          this.staffrightData = res.data.empInfoList;
        })
        .catch((err) => {
          this.$message.error("失败!");
          console.log("debug log --> ", err);
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    // 确认日期
    onOk() {
      this.caeatForm.publishDate = this.date;
    },

    // 定时日期
    onChangeDate(date, dateString) {
      this.date = dateString;
      if (dateString === "") {
        this.caeatForm.publishDate = "";
      }
    },

    // 确认发布
    publish() {
      if (!this.caeatForm.title) {
        this.$message.error("请输入公告标题");
        return;
      }
      if (!this.caeatForm.contentHasStyle) {
        this.$message.error("请输入公告内容");
        return;
      }
      const caeatForm = JSON.parse(JSON.stringify(this.caeatForm));
      console.log("debug log --> ", caeatForm.publishEmpType);
      caeatForm.publishEmpType = caeatForm.publishEmpType.length > 0 ? caeatForm.publishEmpType.join(",") : "";
      caeatForm.noticeType = caeatForm.noticeType.length > 0 ? caeatForm.noticeType.join(",") : "";
      caeatForm.publishEmpRange = JSON.parse(JSON.stringify(caeatForm.publishEmpIds)).join(",");
      caeatForm.file = JSON.stringify(this.fileList);
      console.log("caeatForm", caeatForm);
      screenEmployees(caeatForm).then((res) => {
        this.$router.go(-1);
      });
    },
    // 选择人员
    selectMember() {
      this.visible = true;
    },
    VueWangeditor(html, text) {
      console.log("123", html, text);
      this.caeatForm.contentHasStyle = html;
      this.caeatForm.content = text;
    },
    // 发布范围变动时
    changePublishEmpRangeIsAll(e) {
      this.caeatForm.publishEmpRangeIsAll = e.target.value;
      if (e.target.value) {
        this.defaultSelectedKeys = [];
        this.caeatForm.publishEmpIds = [];
        this.selectedList = [];
        this.fold = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.bleft {
  margin: 0;
  height: 20px;
  padding-left: 12px;
  font-size: 16px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  line-height: 19px;
  border-left: 3px solid var(--primary);
  margin: 24px 0;
}
.wangeditor {
  .home {
    margin: 0 !important;
  }
}
</style>
